<template>
  <view class="h-[88rpx] text-[32rpx] rounded-[12rpx] px-[24rpx] bg-gray-50 flex items-center !border-[#d9d9d9] !border-opacity-100 !border-solid" :class="displayText ? 'text-gray-900' : 'text-gray-400'" @click="openPicker">
    {{ displayText || placeholder }}
  </view>
  <nut-popup v-model:visible="showPicker" position="bottom">
    <nut-picker v-model="pickerValue" :columns="pickerColumns" :readonly="readonly" @confirm="onConfirm" @cancel="showPicker = false" :title="title || placeholder" />
  </nut-popup>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
// import { getDictWithCache } from "../service/api/dict";

interface Props {
  modelValue: string | number | undefined; // 当前选中的值
  columns: Array<Array<{ text: string; value: string | number }>>; // picker的选项数据
  placeholder?: string; // 输入框占位文本
  title?: string; // picker标题，如果不提供则使用placeholder
  dictCode?: string; // 字典码
  readonly?: boolean; // 是否只读
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: "请选择",
  title: "",
});

const emit = defineEmits(["update:modelValue"]);

// 显示控制
const showPicker = ref(false);

// picker选中值 - 使用数组类型
const pickerValue = ref([props.modelValue || '']);

// 本地columns数据，用于存储字典数据
const localColumns = ref<Array<Array<{ text: string; value: string | number }>>>([]);

// 计算最终的picker columns
const pickerColumns = computed(() => {
  if (props.dictCode && localColumns.value.length > 0) {
    return localColumns.value;
  }
  return props.columns;
});

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    pickerValue.value = [newVal || ''];
  }
);

// 监听字典数据变化，确保显示文本能正确更新
watch(
  () => localColumns.value,
  () => {
    // 当字典数据加载完成后，强制更新显示文本
    console.log("字典数据已更新，当前值:", props.modelValue);
  },
  { deep: true }
);

// 计算显示文本
const displayText = computed(() => {
  const currentColumns = pickerColumns.value;
  console.log("displayText computed - currentColumns:", currentColumns);
  console.log("displayText computed - modelValue:", props.modelValue);
  
  if (currentColumns.length === 0 || !props.modelValue) return "";
  
  // 确保在字典数据加载完成后能正确显示
  const option = currentColumns[0].find((item) => {
    // 处理数字和字符串类型的值比较
    const itemValue = typeof item.value === 'number' ? item.value.toString() : item.value;
    const modelValue = typeof props.modelValue === 'number' ? props.modelValue.toString() : props.modelValue;
    console.log("比较:", itemValue, "===", modelValue, "结果:", itemValue === modelValue);
    return itemValue === modelValue;
  });
  
  console.log("找到的选项:", option);
  return option ? option.text : "";
});

const openPicker = () => {
  showPicker.value = true;
};

// 确认选择
const onConfirm = ({ selectedValue, selectedOptions }: any) => {
  console.log("selectedOptions", selectedOptions[0]);
  if (selectedOptions && selectedOptions.length > 0) {
    emit("update:modelValue", selectedOptions[0].value);
  }
  console.log(selectedValue, selectedOptions);
  showPicker.value = false;
};

// 加载字典数据
const loadDictData = async () => {
  if (props.dictCode) {
    // try {
    //   const res = await getDictWithCache(props.dictCode);
    //   if (res && Array.isArray(res)) {
    //     const dictOptions = res.map((item: any) => ({
    //       text: item.itemText,
    //       value: item.itemValue,
    //     }));
    //     localColumns.value = [dictOptions];
    //     console.log("字典数据加载成功:", dictOptions);
    //   }
    // } catch (error) {
    //   console.error("加载字典数据失败:", error);
    // }
  }
};

onMounted(() => {
  console.log("PickerInput mounted");
  loadDictData();
});
</script>
